<template>
    <div class="pageContainer">
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :change-page-size="changePageSize"
            :changePage="changePage" :currentPage="page.page" :pageSize="page.page_size" >
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="addNewCabinet">新增</el-button>
                </template>
                <template #c_activate="{rows}">
                    <el-tag v-if="rows.c_activate == 1" type="success">在线</el-tag>
                    <el-tag v-else type="info">离线</el-tag>
                </template>
                <template #operator="{rows}">
                    <el-button type="primary" text size="small"  @click="handleEdit(rows)">
                        编辑
                    </el-button>
                    <el-button type="danger" text size="small"  @click="handleDelete(rows)">
                        删除
                    </el-button>
                    <el-button type="success" text size="small"  @click="initCabinetInfo(rows)">
                        初始化机柜参数
                    </el-button>
                    <el-button type="warning" text size="small"  @click="setCabinetParams(rows)">
                        设置机柜参数编辑
                    </el-button>
                    <el-popover placement="left" :width="300" trigger="click">
                        <template #reference>
                            <el-button type="info" text size="small">
                                查看包信息
                            </el-button>
                        </template>
                        <div><el-text type="info" >心跳包：<text id="heart">{{ rows.c_heartbeat_code || '122342423' }}</text></el-text><el-button text type="primary"  @click="copyContent(rows.c_heartbeat_code)">复制</el-button></div>
                        <div><el-text type="info" >注册包：<text id="register">{{ rows.c_register_code || '1231324233432' }}</text></el-text><el-button text type="primary" @click="copyContent(rows.c_register_code)">复制</el-button></div>
                    </el-popover>
                </template>
                
            </TableCustom>

        </div>
        <el-dialog :title="diagleTitle" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" :changeCabinetParams="changeCabinetParams"  :chooseArea="choseP"/>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="collaborativeAdministrator-cabinet">
import { ref, reactive, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { Cabinet } from './types/place.js';
import { query_equipment_list, add_update_equipment_info, initialization_equipment, query_list, delete_equipment } from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import useClipboard from 'vue-clipboard3';
import { useRouter } from 'vue-router'
// 查询相关
const query = reactive({
    c_code: null,
    c_manufacturer: null,
    c_activate: null,
    f_code: null
});
// 查询条件相关
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '设备编码', prop: 'c_code', placeholder: '请输入设备编码'},
    { type: 'select', label: '厂家或版本', prop: 'c_manufacturer', placeholder: '请选择厂家或版本' , opts: [{label: '微米', value: '微米'}, {label: '万德昌', value: '万德昌'}],},
    { type: 'select', label: '设备状态', prop: 'c_activate', placeholder: '请选择设备状态', opts: [{label: '离线', value: -1}, {label: '在线', value: 1}] },
    { type: 'select', label: '场地：', prop: 'f_code', placeholder: '请选择场地', opts: [], labelItem: 'f_field_name', valueItem: 'f_code' },

])


const handleSearch = () => {
    console.log(query)
    changePage(1);
};

// 表格相关
let columns = ref([
    {type: 'selection'},
    { prop: 'f_field_name', label: '场地名称', width: 120 },
    { prop: 'c_manufacturer', label: '厂家或版本', width: 120 },
    { prop: 'c_cabinet_name', label: '设备名称', width: 240 },
    { prop: 'c_code', label: '设备编码',width: 160 },
    { prop: 'c_install_area', label: '安装地址', width: 260 },
    
    { prop: 'c_last_end_time', label: '最后在线时间', width: 120
     },
    { prop: 'c_activate', label: '设备状态', width: 90 },

    { prop: 'c_cabinet_num', label: '设备组数',width: 90  },
    { prop: 'c_glasses_layer', label: '眼镜层数',width: 90 },
    { prop: 'c_layer_group', label: '每层组数', width: 90 },
    { prop: 'c_group_glasses_num', label: '每组数量',width: 90 },

    { prop: 'create_time', label: '录入时间',width: 200 },
    { prop: 'operator', label: '操作', width: 380, fixed: 'right' },
])
const page = reactive({
    page: 1,
    page_size: 10,
    total: 0,
})
const tableData = ref<Cabinet[]>([]);
const getData = async() => {
    const res = await query_equipment_list({...query, page: page.page, page_size: page.page_size})
    tableData.value = res.data.data_list;
    page.total = res.data.total;
   
};
let Timer = null


const CircleTimer = () => {
    getData();
    if (Timer) clearInterval(Timer)
    Timer = setInterval(() => {
        getData();
    }, 10 * 1000)
}
CircleTimer()


const changePage = (val: number) => {
    page.page = val;
    CircleTimer()
};
const changePageSize = (val: number) => {
    page.page_size = val;
    getData();
};
onBeforeUnmount(() => {
    clearInterval(Timer)
    console.log(1)
})
// 复制内容

const { toClipboard } = useClipboard()

const copyContent = async (string) => {
    try {
        await toClipboard(string)
        ElMessage({
            type: 'success',
            message: '复制成功',
        })
    }catch (e) {
        console.log(e)
    }
}
const isEdit = ref(false);
// 新增/编辑弹窗相关
let options = ref<FormOption>({
    labelWidth: '150px',
    span: 20,
    list: [
        { type: 'cabinet', label: '厂家或版本', prop: 'c_manufacturer', required: true, placeholder: '请选择厂家或版本',  opts: [{label: '微米', value: '微米'}, {label: '万德昌', value: '万德昌'}]  },
        { type: 'select', label: '场地', prop: 'c_f_code', required: true, placeholder: '请选择场地' , opts: [], valueItem: 'f_code', labelItem: 'f_field_name'},
        { type: 'select', label: '合作管理员', prop: 'c_coomperation_code', required: true, placeholder: '请选择合作管理员', opts: [], labelItem: 'c_user_name', valueItem: 'c_u_code'},

        { type: 'input', label: '设备名称', prop: 'c_cabinet_name', required: false, placeholder: '请输入设备名称' },
        { type: 'input', label: '设备编码', prop: 'c_code', required: false,  placeholder: '请输入设备编码', tips: '请输入设备编码，不输入会自动生成设备编码，并自动绑定到设备' },

        { type: 'input', label: '安装地址', prop: 'c_install_area', required: true, placeholder: '请输入安装地址' },
        
        
        { type: 'input-num', label: '设备组数', prop: 'c_cabinet_num', required: true, placeholder: '请输入设备组数', tips:'最大三层'},
        { type: 'input-num', label: '眼镜层数', prop: 'c_glasses_layer', required: true, placeholder: '请输入眼镜层数' },
        { type: 'input-num', label: '每层组数', prop: 'c_layer_group', required: true, placeholder: '请输入每层组数' },
        { type: 'input-num', label: '每组数量', prop: 'c_group_glasses_num', required: true, placeholder: '请输入每层数量' },
    ]
})
const visible = ref(false);

const rowData = ref({});
const diagleTitle = ref('新增机柜')
const addNewCabinet = async() => {
    let cooperation_user = await query_list({"filter":"cooperation_user"})
    let field = await query_list({"filter":"field"})
    // console.log(cooperation_user, field)
    options.value.list[1].opts = field.data
    options.value.list[2].opts = cooperation_user.data;
    rowData.value= {c_cabinet_num: 1, c_glasses_layer: 5, c_layer_group: 8, c_group_glasses_num: 25};
    options.value.list[4].disabled = false;
    visible.value = true;
    isEdit.value = true;
    
    diagleTitle.value = '新增机柜'
    
}
// 改变数据修改参数
const changeCabinetParams = (data, value) => {
    if (value == '微米') {
        data.c_cabinet_num = 1;
        data.c_glasses_layer = 5;
        data.c_layer_group = 8;
        data.c_group_glasses_num = 25;
    } else {
        data.c_cabinet_num = 2;
        data.c_glasses_layer = 5;
        data.c_layer_group = 8;
        data.c_group_glasses_num = 20;
    }
}
query_list({"filter":"field"}).then(res => {
    searchOpt.value[3].opts = res.data
})
const handleEdit = async (row: Cabinet) => {
    let cooperation_user = await query_list({"filter":"cooperation_user"})
    let field = await query_list({"filter":"field"})
    // console.log(cooperation_user, field)
    options.value.list[1].opts = field.data
    options.value.list[2].opts = cooperation_user.data
    options.value.list[4].disabled = true;
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
     diagleTitle.value = '编辑机柜'
};
const choseP = (data, value) => {
    data.f_province = value[0]
	data.f_city = value[1]
	data.f_area = value[2]
}
const updateData = async(value) => {
    let {c_cabinet_name, c_cabinet_num,c_coomperation_code, c_f_code, c_glasses_layer, c_group_glasses_num, c_install_area, c_layer_group, c_manufacturer, c_code } = value
    const res = await add_update_equipment_info({c_cabinet_name, c_cabinet_num,c_coomperation_code, c_f_code, c_glasses_layer, c_group_glasses_num, c_install_area, c_layer_group, c_manufacturer, c_code})
    if (res.code == '1000') {
        closeDialog();
        CircleTimer();
    }

};

const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
};

// 删除设备
const handleDelete = (rows) => {
    console.log(rows)
    ElMessageBox.confirm(
    '确定要删除此设备?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        delete_equipment({p_c_code: rows.c_code}).then(res => {
            if (res.code === '1000') {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                CircleTimer();
            }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 功能按钮相关
const initCabinetInfo = (row) => {
    ElMessageBox.confirm(
    '初始化机柜参数将会修改设备运行参数，会带来不同程度的影响，是否同意此操作?',
    '重要提示',
    {
      confirmButtonText: '同意',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        ElMessageBox.confirm(
            '确认要初始化参数？',
            '参数初始化',
            {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            }
        ).then(() => {
            initialization_equipment({p_c_code: row.c_code, c_manufacturer: row.c_manufacturer}).then(res => {
                if (res.code === '1000') {
                    ElMessage({
                        type: 'success',
                        message: '初始化数据成功',
                    })
                    CircleTimer();
                }
            })
        })
            
        
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消初始化',
      })
    })
}
const router = useRouter();
const setCabinetParams = (row) => {
    console.log(row)
    router.push({
        name: 'venueManagement-CabinetPrmSet',
        query: {p_c_code: row.c_code, "p_group_code": 1, c_cabinet_num: row.c_cabinet_num},
    })
}
</script>

<style scoped>
.container .cell,.cabinet-container .el-table__cell {
    padding: 0 !important;
}
.container .el-button.is-text {
    padding: 0 !important;
    margin: 0 5px !important;
}
</style>